package com.dubito.tmdbmovie.ui.screen.main


import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.WindowInsetsSides
import androidx.compose.foundation.layout.consumedWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.only
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.material3.DrawerValue
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.NavigationBarItemDefaults
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Snackbar
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.rememberDrawerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.dubito.tmdbmovie.R
import com.dubito.tmdbmovie.common.ConnectionState
import com.dubito.tmdbmovie.common.NavigationDefaults
import com.dubito.tmdbmovie.common.connectivityState
import com.dubito.tmdbmovie.common.pagingLoadingState
import com.dubito.tmdbmovie.ui.component.CircularIndeterminateProgressBar
import com.dubito.tmdbmovie.ui.component.NavigationItem
import com.dubito.tmdbmovie.ui.component.SearchUI
import com.dubito.tmdbmovie.ui.component.appbar.HomeAppBar
import com.dubito.tmdbmovie.ui.component.appbar.SearchBar
import com.dubito.tmdbmovie.ui.navigation.Navigation
import com.dubito.tmdbmovie.ui.navigation.NavigationScreen
import com.dubito.tmdbmovie.ui.navigation.currentRoute
import kotlinx.coroutines.launch


@OptIn(
    ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class,
    ExperimentalAnimationApi::class
)
@Composable
fun MainScreen() {
    val mainViewModel = hiltViewModel<MainViewModel>()
    val navController = rememberNavController()
//    val scaffoldState = rememberScaffoldState()
    val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior()
    val drawerState = rememberDrawerState(DrawerValue.Closed)
    val scope = rememberCoroutineScope()
    val isAppBarVisible = remember { mutableStateOf(true) }
    val searchProgressBar = remember { mutableStateOf(false) }
    val genreName = remember { mutableStateOf("") }
    // genre list for navigation drawer
//    val genres = mainViewModel.genres.value
    // internet connection
    val connection by connectivityState()
    val isConnected = connection === ConnectionState.Available
    val bottomBarVisibility = rememberSaveable {
        mutableStateOf(true)
    }

    // genre api call for first time
    LaunchedEffect(true) {
//        mainViewModel.genreList()
    }

    Scaffold(
        modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
//        scaffoldState = scaffoldState,
        topBar = {
            when (currentRoute(navController)) {
                NavigationScreen.HOME, NavigationScreen.POPULAR, NavigationScreen.TOP_RATED, NavigationScreen.UP_COMING, NavigationScreen.NAVIGATION_DRAWER -> {
                    if (isAppBarVisible.value) {
                        val appTitle: String =
                            if (currentRoute(navController) == NavigationScreen.NAVIGATION_DRAWER)
                                genreName.value
                            else
                                stringResource(R.string.app_title)
                        HomeAppBar(
                            title = appTitle,
                            openDrawer = {
                                scope.launch {
                                    drawerState.apply {
                                        if (isClosed) open() else close()
                                    }
                                }
                            },
                            openFilters = {
                                isAppBarVisible.value = false
                            },
                            scrollBehavior = scrollBehavior
                        )
                    } else {
                        SearchBar(isAppBarVisible, mainViewModel)
                    }
                }
                else -> {
//                    AppBarWithArrow(navigationTitle(navController)) {
//                        navController.popBackStack()
//                    }
                }
            }
        },
//        drawerContent = {
//            // Drawer content
//            if (genres is DataState.Success<Genres>) {
//                DrawerUI(navController, genres.data.genres) {
//                    genreName.value = it
//                    scope.launch {
//                        scaffoldState.drawerState.close()
//                    }
//                }
//            }
//        },
        floatingActionButton = {
//            when (currentRoute(navController)) {
//                NavigationScreen.HOME, NavigationScreen.POPULAR, NavigationScreen.TOP_RATED, NavigationScreen.UP_COMING -> {
//                    FloatingActionButton(
//                        onClick = {
//                            isAppBarVisible.value = false
//                        },
//                        shape = CircleShape
//                    ) {
//                        Icon(Icons.Filled.Search, "", tint = Color.White)
//                    }
//                }
//            }
        },
        bottomBar = {
            when (currentRoute(navController)) {
                NavigationScreen.HOME, NavigationScreen.POPULAR, NavigationScreen.TOP_RATED, NavigationScreen.UP_COMING -> {
                    AnimatedVisibility(
                        visible = bottomBarVisibility.value,
                        enter = slideInVertically(initialOffsetY = { it }),
                        exit = slideOutVertically(targetOffsetY = { it }),
                        content = {
                            BottomNavigationUI(navController)
                        }
                    )
                }
            }
        },
        snackbarHost = {
            if (isConnected.not()) {
                Snackbar(
                    action = {
                    },
                    modifier = Modifier
                        .padding(8.dp)
                ) {
                    Text(text = stringResource(R.string.there_is_no_internet))
                }
            }
        }
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            Navigation(
                isAppBarVisible = isAppBarVisible,
                navController = navController,
                bottomBarVisibility = bottomBarVisibility,
                modifier = Modifier.padding(it).consumedWindowInsets(it)
            )
            Column {
                CircularIndeterminateProgressBar(isDisplayed = searchProgressBar.value, 0.1f)
                if (isAppBarVisible.value.not()) {
                    SearchUI(navController, mainViewModel.searchData) {
                        isAppBarVisible.value = true
                    }
                }
            }
        }
        mainViewModel.searchData.pagingLoadingState {
            searchProgressBar.value = it
        }
    }
}

@Composable
fun BottomNavigationUI(navController: NavController) {
    NavigationBar(
        // 键盘挤压布局
        modifier = Modifier.windowInsetsPadding(
            WindowInsets.safeDrawing.only(
                WindowInsetsSides.Horizontal + WindowInsetsSides.Bottom
            )
        ),
    ) {
        val items = listOf(
            NavigationItem.Home,
            NavigationItem.Popular,
            NavigationItem.TopRated,
            NavigationItem.Upcoming,
        )
        items.forEach { item ->
            NavigationBarItem(
                label = { Text(text = item.title) },
                selected = currentRoute(navController) == item.route,
                colors = NavigationBarItemDefaults.colors(
                    selectedIconColor = NavigationDefaults.navigationSelectedItemColor(),
                    unselectedIconColor = NavigationDefaults.navigationContentColor(),
                    selectedTextColor = NavigationDefaults.navigationSelectedItemColor(),
                    unselectedTextColor = NavigationDefaults.navigationContentColor(),
                    indicatorColor = NavigationDefaults.navigationIndicatorColor()
                ),
                icon = item.icon,
                onClick = {
                    navController.navigate(item.route) {
                        navController.graph.startDestinationRoute?.let { route ->
                            popUpTo(route) {
                                saveState = true
                            }
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                }
            )
        }
    }
}